package com.itboye.ihomebank.zjtlcb.lnd.livenessdetector.utils.security;


import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;


/**
 * 描述:${Description}
 * 创建者:victor
 * 邮箱: victorwangk@qq.com
 * SDK
 * 日期:2017/8/18
 */

public class Hmac {

    private final static String HMACSHA1="HmacSHA1";

    public String encode(byte[] key, byte[] str) {
        try {
            SecretKeySpec singingKey = new SecretKeySpec(key, HMACSHA1);
            Mac mac = null;

            mac = Mac.getInstance(HMACSHA1);

            mac.init(singingKey);
            byte[] signByte = mac.doFinal(str);
            StringBuilder sb = new StringBuilder();
            for (byte b : signByte) {
                sb.append(byteToHexString(b));
            }
            String sign = sb.toString().toUpperCase();
            return sign;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String byteToHexString(byte ib) {
        char[] digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] ob = new char[2];
        ob[0] = digit[(ib >>> 4) & 0X0f];
        ob[1] = digit[ib & 0X0f];
        String s = new String(ob);
        return s;
    }

    public String encrypt(String encryptKey, String encryptString) throws Exception {
        return encode(encryptKey.getBytes(),encryptString.getBytes());
    }

    public String decrypt(String decryptKey, String decryptString) throws Exception {
        return null;
    }
}
